package com.zz.ecommerce.togatherDeclareMgr.custDeclarationUpload.service;


import com.zz.ecommerce.common.constants.TableConstants;
import com.zz.ecommerce.togatherDeclareMgr.common.bean.TCargo;
import com.zz.ecommerce.togatherDeclareMgr.common.bean.TContainers;
import com.zz.ecommerce.togatherDeclareMgr.common.bean.TDocuments;
import com.zz.ecommerce.togatherDeclareMgr.common.bean.TEntryInfo;
import com.zz.ecommerce.togatherDeclareMgr.custDeclarationUpload.TemplateMap;
import com.zz.ecommerce.togatherDeclareMgr.custDeclarationUpload.bean.DecMessage;
import com.zz.ecommerce.togatherDeclareMgr.custDeclarationUpload.bean.MsgDecHistory;
import com.zz.ecommerce.togatherDeclareMgr.custDeclarationUpload.dao.CargoCustDao;
import com.zz.ecommerce.utils.DateUtil;
import com.zz.ecommerce.utils.FreeMarkerUtil;
import com.zz.ecommerce.utils.ZzStringUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;

/**
 * <一句话功能描述>
 * <功能详细描述>
 *
 * @author Administrator
 * @date 2015/8/15,16:33
 */
@Service
public class DecMessageService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private CargoCustDao cargoCustDao;

    @Autowired
    private TemplateMap templateMap;

    @Value("${cust.json.store.path}")
    private String msgSavePath;

    public String getDecMesseageJson(final String indx, final String promiseItmes) {
        DecMessage decMessage = getDecMessage(indx);

        decMessage.setPromiseItmes(promiseItmes); //承诺事项

        String msgJson = "{}";
        try {
            msgJson = FreeMarkerUtil.processTemplate(templateMap.getTemplateMap().get(DecMessage.class.getSimpleName())
                                                         .getTemplate(), decMessage);
            final String saveJsonStr = msgJson;

            //保存上传的json文件
            new Thread(new Runnable() {
                @Override
                public void run() {
                    File dir = new File(msgSavePath);
                    if (!dir.isDirectory()) {
                        dir.mkdirs();
                    }
                    String saveJsonFile = msgSavePath + "/" + indx + "_" + DateUtil.getCurrentTime
                        ("yyyyMMddHHmmss") + ".json";
                    try {
                        FileUtils.writeByteArrayToFile(new File(saveJsonFile), saveJsonStr.getBytes("utf-8"));
                    } catch (IOException e) {
                        log.error("saveJsonFile----->IOException", e);
                    }
                }
            }).start();

        } catch (IOException e) {
            log.error("加载" + DecMessage.class.getName() + "模板失败", e);
            return "";
        }
        return msgJson;
    }

    /**
     * 获取报关报文
     *
     * @param indx
     * @return
     */
    public DecMessage getDecMessage(String indx) {
        DecMessage decMessage = new DecMessage();
        if (StringUtils.isNotEmpty(indx)) {
            //获取报关报文头
            TEntryInfo qryHead = new TEntryInfo();
            qryHead.setConIndx(indx);

            // 目前预录入编号为18位，海关组件还没有支持18位，需要截取上报海关 TODO
            TEntryInfo entryInfo = cargoCustDao.queryEntryInfo("T_ENTRYINFO", qryHead, "");
            if (StringUtils.isNotEmpty(entryInfo.getPreentryid()) && entryInfo.getPreentryid().length() == 18) {
                entryInfo.setPreentryid(entryInfo.getPreentryid().substring(9));
            }

            decMessage.setDecHead(entryInfo);
            //获取报关获取信息
            TCargo qryCargo = new TCargo();
            qryCargo.setConIndx(indx);
            decMessage.setDecLists(cargoCustDao.queryAllCargo("T_CARGO", qryCargo, ""));
            //获取集装箱信息
            TContainers qryContainer = new TContainers();
            qryContainer.setConIndx(indx);
            decMessage.setDecContainers(cargoCustDao.queryAllContainer("T_CONTAINERS", qryContainer, ""));
            //获取随附单据信息
            TDocuments qryDocument = new TDocuments();
            qryDocument.setConIndx(indx);
            decMessage.setDecLicenseDocus(cargoCustDao.queryAllDocument("T_DOCUMENTS", qryDocument, ""));
            decMessage.setClientSeqNo(getClientSeqNo());
        }
        return decMessage;
    }


    /**
     * 获得企业唯一编号
     *
     * @return
     * @TODO:需要对接真正的企业编号
     */
    public String getClientSeqNo() {
        return ZzStringUtil.getMsSendTime();
    }

    @Transactional
    public boolean updateDeclareCustStatus(String conIndx, String status) {

        TEntryInfo entryInfo = new TEntryInfo();
        entryInfo.setConIndx(conIndx);
        entryInfo.setDeclareda(ZzStringUtil.getNowTime("yyyy-MM-dd hh:mm:ss"));
        entryInfo.setStatus(status);

        cargoCustDao.updateDeclareCustStatus(conIndx, status);

        syncCustStatus(status, "已上传", conIndx);

        return true;
    }

    private void syncCustStatus(String msgCode, String msgDesc, String conIndx) {
        MsgDecHistory msgDecHistory = new MsgDecHistory();
        msgDecHistory.setClientSeqNo(conIndx);
        msgDecHistory.setCreateTime(ZzStringUtil.getDefaultDateTime());
        msgDecHistory.setErrorMessage(msgDesc);
        msgDecHistory.setResponseCode(msgCode);

        cargoCustDao.inserMsgDecHistory(TableConstants.MSG_DEC_HISTORY, msgDecHistory);
    }
}
